package vn.qnamuni.calendar.services;

import vn.qnamuni.calendar.activity.R;
import vn.qnamuni.calendar.activity.ListActivity;
import vn.qnamuni.calendar.activity.ViewActivity;
import vn.qnamuni.calendar.constants.PersonContract;
import vn.qnamuni.calendar.providers.MyContentProvider;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

/*
 * We also need to implement a Service that represents 
 * the application�s need to run a longer operation 
 * in the background without interacting with the user. 
 * For this purpose let�s create a Service called MyAlarmService.
 */
public class MyAlarmService extends Service {
	public static int AUTOSMS = 1;
	public static int EARLIER = 2;
	public static int MANUALSMS = 3;

	static int count = 0;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// here you can start an activity or service depending on your need
		// for ex you can start an activity to vibrate phone or to ring the
		// phone
		try {
			int id = intent.getIntExtra(PersonContract.Entry.KEY_ID, -1);
			if (id >= 1000) {
				id = id - 1000;
			}
			String[] projection = {
					PersonContract.Entry.KEY_ID, // 0
					PersonContract.Entry.KEY_UID, // 1
					PersonContract.Entry.KEY_NAME,// 2
					PersonContract.Entry.KEY_MESSAGE,// 3
					PersonContract.Entry.KEY_PHONE, // 4
					PersonContract.Entry.KEY_USERNAME,
					PersonContract.Entry.KEY_MODE };// 5

			Cursor c = this.getContentResolver().query(
					MyContentProvider.CONTENT_URI, projection,
					PersonContract.Entry.KEY_ID + " LIKE ?",
					new String[] { "%" + String.valueOf(id) + "%" }, null);
			c.moveToFirst();
			if (0 == c.getCount()) {
				return;
			}
			String name = c.getString(2);
			String message = c.getString(3);
			String phone = c.getString(4);
			String username = c.getString(5);
			String nmode = c.getString(6);
			// mode = c.getInt(6);
			// Toast.makeText(this.getApplicationContext(),
			// "Alarm Triggered and SMS Sent to" + name, Toast.LENGTH_LONG)
			// .show();

			// notify
			// 3 mode: notify, auto send sms, 7 earlier
			if (nmode.equals("1")) {
				// on date
				sendAutoSms(id, phone, message);
				createNotification(this.getApplicationContext(), name,
						username, phone, message, id);
			} else {
				// 7 earlier
				// no action
				createNotification(this.getApplicationContext(), name,
						username, phone, message, id);
			}
		} catch (Exception e) {
			Log.v("Alarm Service Exceptin", e.getMessage());
		}
	}

	public Intent view(int id) {
		Intent viewIntent = new Intent(this.getApplicationContext(),
				ViewActivity.class);
		Uri todoUri = Uri.parse(MyContentProvider.CONTENT_URI + "/" + id);
		viewIntent.putExtra(MyContentProvider.CONTENT_ITEM_TYPE, todoUri);
		return viewIntent;
	}

	public Intent postWall(String username, String message) {
		Intent pstIntent = new Intent(this.getApplicationContext(),
				ListActivity.class);
		pstIntent.putExtra("action", FacebookService.POST_WALL);
		pstIntent.putExtra(PersonContract.Entry.KEY_USERNAME, username);
		pstIntent.putExtra(PersonContract.Entry.KEY_MESSAGE, message);
		return pstIntent;
	}

	public void sendAutoSms(int id, String phone, String message) {
		try {
			if (null != phone && !phone.equals("null") && !phone.equals("")) {
				SmsManager sms = SmsManager.getDefault();
				sms.sendTextMessage(phone, null, message, null, null);
				Toast.makeText(getApplicationContext(),
						"auto SMS Sent to " + phone, Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(
						this,
						"Sorry, we cannot not send message because the phone is not exist",
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"SMS faild, please try again later!", Toast.LENGTH_LONG)
					.show();
			e.printStackTrace();
		}
	}

	public Intent sendManualSms(int id, String phone, String message) {
		if (null != phone && !phone.equals("null")) {
			Intent sendIntent = new Intent(Intent.ACTION_VIEW);
			sendIntent.putExtra("sms_body", message);
			sendIntent.putExtra("address", phone);
			sendIntent.setType("vnd.android-dir/mms-sms");
			// need?
			sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			return sendIntent;
		} else {
			return view(id);
		}
	}

	public Intent call(String phone) {
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:" + phone));
		return callIntent;
	}

	protected void createNotification(Context context, String title,
			String username, String phone, String message, int id) {
		final String NOTIFICATION_SERVICE = android.content.Context.NOTIFICATION_SERVICE;
		// Prepare intent which is triggered if the
		// notification is selected
		Log.v("noti", title + " ");
		Intent viewIntent = view(id);
		Intent sendIntent = sendManualSms(id, phone, message);
		Intent callIntent = call(phone);
		Intent postIntent = postWall(username, message);

		PendingIntent pviewIntent = PendingIntent.getActivity(context, 0,
				viewIntent, 0);
		PendingIntent psendIntent = PendingIntent.getActivity(context, 0,
				sendIntent, 0);
		PendingIntent pcallIntent = PendingIntent.getActivity(context, 0,
				callIntent, 0);
		PendingIntent ppostIntent = PendingIntent.getActivity(context, 0,
				postIntent, 0);
		// Build notification
		// Actions are just fake
		Notification noti = new Notification.Builder(context)
				.setContentTitle("Birthday")
				.setContentText(title)
				.setSmallIcon(R.drawable.ic_launcher)
				// Intent when click
				.setContentIntent(pviewIntent)
				// extendible intents
				.setAutoCancel(true)
				// .setStyle(new Notification.BigTextStyle().bigText("Gogod"))
				.addAction(R.drawable.ic_sms, "Send", psendIntent)
				.addAction(R.drawable.ic_call, "Call", pcallIntent)
				.addAction(R.drawable.ic_post, "Post", ppostIntent).build();

		// call service
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(NOTIFICATION_SERVICE);
		// hide the notification after its selected
		noti.flags |= Notification.FLAG_AUTO_CANCEL;

		// different id notify
		notificationManager.notify(count++, noti);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}